<template>
  <el-dialog
    title="个人报名"
    :visible.sync="visible"
    width="70%"
    class="dialog-person-registration"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="addPersonRules" label-width="120px">
      <el-form-item label="报名项目" prop="projectId">
        <treeselect
          v-model="form.projectId"
          :options="projectOptions"
          :default-expand-level="Infinity"
          placeholder="请选择项目"
        />
      </el-form-item>

      <el-form-item label="培训类别" prop="trainingType">
        <el-select v-model="form.trainingType" placeholder="请选择培训类别">
          <el-option label="1" value="新训" />
          <el-option label="2" value="复训" />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="studentName">
        <el-input v-model="form.studentName" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
      </el-form-item>

      <el-form-item label="证件类型" prop="certificateType">
        <el-select v-model="form.certificateType" placeholder="请选择证件类型">
          <el-option label="身份证" value="idCard" />
        </el-select>
      </el-form-item>

      <el-form-item label="证件号码" prop="idNumber">
        <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
      </el-form-item>

      <el-form-item label="证件有效期">
        <el-date-picker
          v-model="form.idValidDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="出生年月" prop="birthDate">
        <el-date-picker
          v-model="form.birthDate"
          type="date"
          format="yyyy-MM-dd"
          placeholder="请选择出生年月"
        />
      </el-form-item>

      <el-form-item label="学历" prop="qualification">
        <el-input v-model="form.qualification" placeholder="请输入学历" />
      </el-form-item>

      <el-form-item label="工作单位">
        <el-input v-model="form.workUnit" placeholder="请输入工作单位" />
      </el-form-item>

      <el-form-item label="工作时间">
        <el-date-picker
          v-model="form.workPeriod"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-button type="text" @click="addPersonWorkExperience">添加到工作简历</el-button>
      </el-form-item>

      <el-form-item label="工作简历">
        <el-textarea
          v-model="form.workResume"
          rows="4"
          placeholder="请输入工作简历内容"
        />
      </el-form-item>

      <el-form-item label="档案缺失情况">
        <el-checkbox-group
          v-model="form.recordMissing"
          @change="handleArchiveMissingChange"
        >
          <el-checkbox label="全缺" />
          <el-checkbox label="照片" />
          <el-checkbox label="申请表" />
          <el-checkbox label="身份证" />
          <el-checkbox label="学历证明" />
          <el-checkbox label="体检证明" />
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitPersonForm('form')">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { projectTreeSelect } from "@/api/training/projects";
import { addPerson } from "@/api/training/registration";

export default {
  components: { Treeselect },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    projectId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      form: {
        subjectId: "",
        trainingClass: "",
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        certificateStarttime: "",
        certificateEndtime: "",
        sex: "男",
        birthDate: "",
        nation: "",
        qualification: "",
        school: "",
        major: "",
        address: "",
        zipcode: "",
        fax: "",
        email: "",
        companyName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "enterprise",
        contact: "",
        unitPhonenumber: "",
        recordMissing: [],
        agreementStatus: false,
        remark: "",
        workPeriod: [],
        workUnit: "",
        workResume: "请输入工作简历内容，可自由编辑",
        projectId: ""
      },
      addPersonRules: {
        projectId: [
          { required: true, message: "请选择报名项目", trigger: "change" }
        ],
        trainingType: [
          { required: true, message: "请选择培训类别", trigger: "change" }
        ],
        studentName: [
          { required: true, message: "请输入姓名", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" }
        ],
        certificateType: [
          { required: true, message: "请选择证件类型", trigger: "change" }
        ],
        idNumber: [
          { required: true, message: "请输入证件号码", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        birthDate: [
          { required: true, message: "请选择出生年月", trigger: "change" }
        ],
        qualification: [
          { required: true, message: "请输入学历", trigger: "blur" }
        ]
      },
      projectOptions: [],
      archiveIndexToLabelMap: {
        0: "全缺",
        1: "照片",
        2: "申请表",
        3: "身份证",
        4: "学历证明",
        5: "体检证明"
      },
      archiveLabelToIndexMap: {
        全缺: 0,
        照片: 1,
        申请表: 2,
        身份证: 3,
        学历证明: 4,
        体检证明: 5
      }
    };
  },
  created() {
    this.getProjectTree();
    if (this.projectId) {
      this.form.projectId = this.projectId;
    }
  },
  methods: {
    getProjectTree() {
      projectTreeSelect({}).then(response => {
        this.projectOptions = response.data;
      });
    },
    handleArchiveMissingChange(value) {
      if (value.includes("全缺")) {
        this.form.recordMissing = [
          "全缺",
          "照片",
          "申请表",
          "身份证",
          "学历证明",
          "体检证明"
        ];
      } else if (
        !value.includes("全缺") &&
        this.form.recordMissing.includes("全缺")
      ) {
        this.form.recordMissing = [];
      } else {
        this.form.recordMissing = value;
      }
    },
    addPersonWorkExperience() {
      const workPeriod = this.form.workPeriod;
      const workUnit = this.form.workUnit;

      if (Array.isArray(workPeriod) && workPeriod.length === 2 && workUnit) {
        const start = workPeriod[0];
        const end = workPeriod[1];
        const newExperience = `${start}至${end}，在${workUnit}从事特种设备安全管理工作`;

        this.form.workResume += `\n${newExperience}`;
        this.form.workPeriod = [];
        this.form.workUnit = "";
      } else {
        this.$message.warning("请完整填写工作时间和工作单位");
      }
    },
    submitPersonForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let submitForm = { ...this.form };

          // 处理档案缺失字段转换
          if (Array.isArray(submitForm.recordMissing) && submitForm.recordMissing.length > 0) {
            const indices = submitForm.recordMissing
              .map(label => this.archiveLabelToIndexMap[label])
              .filter(index => index !== undefined);
            submitForm.recordMissing = indices.join(",");
          } else {
            submitForm.recordMissing = "";
          }

          // 处理证件有效期
          if (Array.isArray(submitForm.idValidDate) && submitForm.idValidDate.length === 2) {
            submitForm.certificateStarttime = submitForm.idValidDate[0];
            submitForm.certificateEndtime = submitForm.idValidDate[1];
          } else {
            submitForm.certificateStarttime = "";
            submitForm.certificateEndtime = "";
          }
          delete submitForm.idValidDate;

          addPerson(submitForm).then(response => {
            if (response.code === 200) {
              this.$message.success("新增成功");
              this.$emit("success");
              this.handleClose();
            } else {
              this.$message.error("新增失败: " + response.msg);
            }
          });
        } else {
          this.$message.warning("请填写必填项");
          return false;
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    }
  }
};
</script>
